const App = {
  mixins: [Save], //配置文件，路径/utils/mixins.js
  data() {
    return {
      originalTableData2: [],
      selectedCount: 0,
      filterText: "",
      treeData: [],
      checkboxOptions2: [],
      // 复选框选项数组
      checkboxOptions: [],
      // 选中的选项值数组
      selectedOptions: [],

      childDataForm: [{}],
      tableData: [],

      dialogFormVisible: false,

      taskPlan_SerialNumber: "",
      team_SerialNumber: "",
      Task_SerialNumber: "",
      SendMessageCount: 0,
      Membertotal: 0
    };
  },
  mounted() {
    let ls_URL = window.location.href;

    this.taskPlan_SerialNumber = getQueryObject(ls_URL, "nodeKey");

    this.team_SerialNumber = getQueryObject(ls_URL, "team_SerialNumber");

    this.Task_SerialNumber = getQueryObject(ls_URL, "Task_SerialNumber");

    this.Getplan_memberAndSetData(this.taskPlan_SerialNumber, this.team_SerialNumber);



  },
  watch: {

  },
  methods: {


    cren(Arg_res) {
      const _this = this;
      //为人员列表赋值
      _this.checkboxOptions = _this.checkboxOptions2;

      $.ajax({
        headers: requestHeaders(),

        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
        method: "POST",
        data: {
          Data: 'patrol_taskPlan_member', //sql名
          Condition: "Row_Status='0' and taskPlan_SerialNumber='" + Arg_res + "'"
        },
        success: (res) => {
          console.log("接口返回数据:", res);

          if (res.length > 0) {

            // 2. 保存原始成员数据（含职务、时间）
            _this.originalTableData2 = res;
            //页面表格上的
            _this.tableData = res;

            _this.childDataForm = res;


            // 处理复选框：过滤负责人，保留已选状态



            _this.setCheckboxesSelected(res);; // 恢复选中状态

          }
          else {


          }
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });


    },

    // 设置复选框选中状态的方法
    setCheckboxesSelected(selectedMembers) {
      console.log(
        "设置复选框选中状态，已选中成员数量:",
        selectedMembers.length
      );

      const selectedIds = selectedMembers.map(
        (member) => member.ID_Card_Number
      );
      // const captainId = this.childDataForm[0]?.ID_Card_Number;
      const selectedIdMap = new Map(selectedIds.map(id => [id, true]));

      this.checkboxOptions.forEach(option => {
        // if (option.ID_Card_Number === captainId) {
        //   option.checked = false;
        //   return;
        // }

        const isSelected = selectedIdMap.has(option.ID_Card_Number);
        option.checked = isSelected;
        console.log(`成员 ${option.Personal_Name} 选中状态:`, isSelected);
      });



      this.updateSelectedCount();
      this.handleCheckboxChange();
      console.log("设置完成，当前已选数量:", this.selectedCount);
    },

    handleCheckboxChange(option) {

      let _this = this;
      const selectedMembers = _this.checkboxOptions.filter(
        (option) =>
          option.checked
      );
      console.log("watch1", this.tableData)

      this.tableData = selectedMembers.map((option) => {
        const original = this.originalTableData2.find(
          (item) => item.ID_Card_Number === option.ID_Card_Number
        );

        //​覆盖策略​：默认行为（无需额外处理）
        return {
          ...original,  //将 option 对象的所有可枚举属性浅拷贝到新对象中，作为基础属性
          Contact_Phone: option.Contact_phone || "", // 确保使用option对象优先使用 original.Mobile，若不存在则回退到 option.Contact_Phone，最后保底为空字符串

          Personal_Name: option?.Personal_Name || "",
          ID_Card_Number: option?.ID_Card_Number || ""

        };
      });
      console.log("watch2", this.tableData)

      this.updateSelectedCount();
    },


    // 清空选中并移除选项
    clearAll() {

      // 没有负责人时，清空列表
      this.checkboxOptions = [];


      // 更新已选数量
      this.updateSelectedCount();
    },
    // 更新已选数量
    updateSelectedCount() {
      this.selectedCount = this.checkboxOptions.filter(
        (option) => option.checked
      ).length;
    },

    handleNodeClick(data) {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: "post",
        data: {
          SQLSerialNumber: "f_party_member_information",
          Condition: "",
          ExtensionCondition: window.btoa(
            unescape(
              encodeURIComponent(
                "AND party_member_information.Party_Organization_SerialNumber='" +
                data.Party_Organization_SerialNumber +
                "'"
              )
            )
          ),
        },
        success: (newMembers) => {
          console.log("获取到新的人员列表:", newMembers);


          // 创建一个映射，用于快速查找已存在的人员
          const existingMap = {};
          _this.checkboxOptions.forEach((member) => {
            existingMap[member.ID_Card_Number] = member;
          });

          // 合并新的人员列表到现有列表，排除当前负责人
          newMembers.forEach((newMember) => {


            // 如果人员已存在，保留其选中状态
            if (existingMap[newMember.ID_Card_Number]) {
              Object.assign(existingMap[newMember.ID_Card_Number], newMember);
            } else {
              // 添加新人员，并默认设置为未选中
              _this.checkboxOptions.push({
                ...newMember,
                checked: false,
              });
            }
          });

          // 更新已选数量
          _this.updateSelectedCount();

          console.log("合并后的人员列表:", _this.checkboxOptions);
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },





    handleSubmit2() {
      let _this = this;

      console.log("提交前", _this.tableData)

      console.log("提交前原值", _this.originalTableData2)



      //比对tableData内的记录与originalTableData2记录的差异,
      // 如果tableData不包含originalTableData2则插入tableData一条带原值的Row_status=1的记录,代表删除
      const ltableData = _this.originalTableData2.map(option => {
        // const original = _this.tableData.find(
        //   item => item.ID_Card_Number === option.ID_Card_Number
        // );

        const bhas = _this.tableData.some(
          item => item.ID_Card_Number === option.ID_Card_Number
        );

        // ​覆盖策略​：默认行为（无需额外处理）
        // ​合并值​：若需保留所有值，可将重复键的值合并为数组：

        if (!bhas) {
          return {
            ...option,  //将 option 对象的所有可枚举属性浅拷贝到新对象中，作为基础属性

            Row_Status: "1"

          };
        }

      });
      //将undefined的条目清理
      const cleaned = ltableData.filter(item => item !== undefined);

      if (cleaned.length > 0) {
        _this.tableData.push(...cleaned);
      }

      console.log("处理完Row_Status", _this.tableData)

      //调用 通用的提交方法
      _this.handleSubmit1();
    },


    Getplan_memberAndSetData(Arg1, Arg2) {
      const _this = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data: {
          SQLSerialNumber: "SQL_patrol_member_list", //sql名
          Condition: "", //不必选的条件
          ExtensionCondition: window.btoa(
            unescape(
              encodeURIComponent(
                " where patrol_member.Row_Status='0' and  patrol_member.team_SerialNumber='" + Arg2 + "'"
              ))),
        },
        success: (res) => {
          console.log(res);
          _this.checkboxOptions2 = res;
          _this.cren(Arg1);
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },

    xin() {
      this.dialogFormVisible = true;
    },
    async handleSubmit1() {
      const allValid = await this.validateAllForms();
      if (allValid) {
        this.loading = true;
        let ls_URL = window.location.href;
        const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
        let lJSONObject_Data_Options = new Object();
        lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

        let ls_MainTableName = lJSONObject_Data_Options.TableName;
        let ls_DataForm = lJSONObject_Data_Options.form;
        let ls_primary_key = lJSONObject_Data_Options.primary_key;
        //没有子表下面内容就会报错，try/catch抛出异常
        try {
          //可能涉及多个子表
          document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
            if (item.hasAttribute('data-options')) {
              let lJSONObject_ChildData_Options = new Object();
              lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

              let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
              let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
              // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
              if (this[ls_DataForm][ls_primary_key]) {
                this[ls_ChildDataForm].forEach(item => {
                  item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                })
              }
              //建立子表结构体
              let JSONArray_ChildRecord = new Array();
              JSONArray_ChildRecord = this[ls_ChildDataForm];
              if (!this[ls_DataForm].Children) {
                this[ls_DataForm].Children = new Object();
              }
              this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
            }
          })
        } catch (error) {

        }
        //建立新增提交结构
        let lJSONObject_DataSet = new Object();
        if (action == 'Add') {
          if (this.nodeKey) {
            this[ls_DataForm].Parent_SerialNumber = this.nodeKey;
          }
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(this[ls_DataForm]);
          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
          lJSONObject_DataSet[action] = lJSONObject_Table;
        } else if (action == 'Modify') {
          const { add, modify } = this.deal(this[ls_DataForm]);
          let lJSONArray_Record = new Array();
          lJSONArray_Record.push(modify);

          let lJSONObject_Table = new Object();
          lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

          lJSONObject_DataSet[action] = lJSONObject_Table;
          lJSONObject_DataSet['Add'] = new Object();
          if (add != null) {
            let lJSONArray_Record_Add = new Array();
            lJSONArray_Record_Add.push(add);

            let lJSONObject_Table_Add = new Object();
            lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

            lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
          }
        }
        let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
        lJSONObject_DataSet['Add']['base_operation_log'] = [{
          Operation_Type: '0',
          Operation_Path: this.relativePath,
          Operation_Main,
          Operation_Interface: "generalSaveByRequestBody",
          Operation_IP: getIpAddress()
        }]
        console.log(lJSONObject_DataSet);

        submitSave(lJSONObject_DataSet, (res) => {
          if (res.Status == 'success') {

            //给队员发送消息
            this.SendMessageCount = 0;
            //查询需要发送消息的所有队员

            $.ajax({

              headers: requestHeaders(),
              url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
              method: "post",
              data: {
                SQLSerialNumber: "SQL_patrol_taskPlan_member_sendmessage", //sql名
                Condition: "", //不必选的条件
                ExtensionCondition: window.btoa(
                  unescape(
                    encodeURIComponent(
                      " where patrol_taskPlan_member.Row_Status='0' and patrol_taskPlan_member.taskPlan_SerialNumber='" + this.taskPlan_SerialNumber + "'"
                    ))),
              },
              success: (data) => {
                this.Membertotal = data.length;
                this.SendMessageCount = 0;
                if (this.Membertotal > 0) {
                  data.map(item => {
                    this.seedMessage(item);
                  })


                } else {
                  window.location.href = "./index_taskPlan.html?action=Query&nodeKey=" + this.Task_SerialNumber + "&team_SerialNumber=" + this.team_SerialNumber;
                }
              },
              complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest);

              },
              dataType: "json",


            })

          }
          this.loading = false;
        })

      } else {
        this.$message({
          message: '存在未填写的必填项！',
          type: 'warning'
        });
      }
    },
    // 模板IDtP5n7jHkEiY-ay0kEBmn14wQNEnmNRUenefcMlKGE3s
    // 模板编号5771
    // 标题事项办理进度通知
    // 类目政务服务大厅
    // 操作人__****17 2025-09-19 添加
    // 详细内容申请人{{name1.DATA}}
    // 事项名称{{thing2.DATA}}
    // 当前进度{{thing3.DATA}}
    // 创建时间{{date7.DATA}}
    // 备注{{thing9.DATA}}
    // 场景说明事件类办理等
    seedMessage(itemtaskPlan_member) {
      //获取人员名称以及OPENID
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data: {
          SQLSerialNumber: "SQL_GetUserNameAndOpenID",
          Condition: '',
          ExtensionCondition: window.btoa(unescape(encodeURIComponent(" where personal_information.ID_Card_Number ='" + itemtaskPlan_member.ID_Card_Number + "' ")))
        },
        success: (res1) => {
          if (res1.length > 0) {
            const lopenid = res1[0].OpenID;
            const lname = res1[0].Personal_Name;
            const lServerdatetime = res1[0].Serverdatetime;
            //调用消息发送接口
            $.ajax({
              headers: requestHeaders('JSON'),
              url: `${mh}/requestForward/requestForwardForPost?RequestURL=${encodeURIComponent(`/wx/mp/sendMicroProgramTemplateMessage`)}`,
              method: "POST",
              data: JSON.stringify({
                openId: lopenid,
                templateId: "tP5n7jHkEiY-ay0kEBmn14wQNEnmNRUenefcMlKGE3s",
                content: {
                  name1: { value: "巡边系统" },
                  thing2: { value: "巡边任务下发，日期：" + itemtaskPlan_member.PlanDate },
                  thing3: { value: '任务下发，待完成' },
                  date7: { value: lServerdatetime },
                  thing9: { value: "任务号：" + this.Task_SerialNumber },
                }
              }),
              success: (res) => {

              },
              complete: (XMLHttpRequest) => {
                requestPretreatment(XMLHttpRequest)
                this.SendMessageCount++;
                if (this.SendMessageCount == this.Membertotal) {
                  window.location.href = "./index_taskPlan.html?action=Query&nodeKey=" + this.Task_SerialNumber + "&team_SerialNumber=" + this.team_SerialNumber;
                }
              },

            });
          } else {
            this.SendMessageCount++;
            if (this.SendMessageCount == this.Membertotal) {
              window.location.href = "./index_taskPlan.html?action=Query&nodeKey=" + this.Task_SerialNumber + "&team_SerialNumber=" + this.team_SerialNumber;
            }
          }
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });



    },
  },
};

const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
